package com.cxh.rmsq.ui.fragment.self

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.db.model.CommunityContent
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.adapter.self.CircleListAdapter
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.lxj.xpopup.XPopup
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.rong.imkit.RongIM


private const val ARG_PARAM1 = "param1"

class MineTrendsListFragment : BaseFragment(), CircleListAdapter.OnCustomClickListener {
    private var param1: Int? = 0
    private lateinit var refreshList: SmartRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private var listAdapter: CircleListAdapter? = null
    private var page = 1
    private val imagesMediaList = java.util.ArrayList<LocalMedia>()

    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }

    companion object {
        fun newInstance(param1: Int): MineTrendsListFragment {
            val fragment = MineTrendsListFragment()
            val args = Bundle()
            args.putInt(ARG_PARAM1, param1)
            fragment.arguments = args
            return fragment
        }
    }


    override fun getLayoutResId(): Int {
        return R.layout.fragment_mine_trends_list
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        param1 = requireArguments().getInt(ARG_PARAM1)

        refreshList = view.findViewById(R.id.refresh_list) as SmartRefreshLayout
        recyclerView = view.findViewById(R.id.rv_list) as RecyclerView

        recyclerView.layoutManager = LinearLayoutManager(context)
        listAdapter = CircleListAdapter(param1!!, this) //1  2草稿箱
        listAdapter!!.setEmptyView(View.inflate(activity, R.layout.empty_data_layout, null))
        recyclerView.adapter = listAdapter
        listAdapter!!.setOnItemClickListener { adapter, view, position -> }
        listAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_like -> {
                    var type = 0
                    type = if (listAdapter!!.data[position].isLiked == 1) { //已点赞
                        0
                    } else {
                        1
                    }
                    val paramsMap = HashMap<String, Any>()
                    paramsMap["busId"] = listAdapter!!.data[position].id
                    paramsMap["userId"] = IMManager.getInstance().currentId
                    paramsMap["type"] = 1 //1动态2评论
                    paramsMap["isLiked"] = type //1:点赞 0：取消
                    paramsMap["bdzUserId"] = listAdapter!!.data[position].userId //被点赞用户id,
                    viewModel.commentLiked(paramsMap) {
                        if (it.code == 200) {
                            getData()
                        } else {
                            com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
                        }
                    }
                }
            }
        }

        refreshList.resetNoMoreData()
        refreshList.setRefreshHeader(MaterialHeader(activity))
        refreshList.setRefreshFooter(ClassicsFooter(activity))
        refreshList.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                getData()
                refreshLayout.finishLoadMore()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
//                dataList.clear()
                listAdapter!!.setNewInstance(null)
                getData()
            }
        })
    }

    override fun onResume() {
        super.onResume()
        page = 1
        listAdapter!!.setNewInstance(null)
        getData()

    }

    private fun getData() {
        if (param1 == 1) {
            viewModel.getselectByPage(
                IMManager.getInstance().currentId,
                page,
                10
            ) {
                Log.e("total", it.data.total.toString() + "")
                if (refreshList.isRefreshing) {
                    refreshList.finishRefresh()
                }
                if (it.data != null) {
                    if (page == 1) {
                        listAdapter!!.setNewInstance(it.data.list)
                        if (it.data.list!!.size < 10) {
                            refreshList.setEnableLoadMore(false)
                        } else {
                            refreshList.setEnableLoadMore(true)
                        }
                    } else {
                        if (it.data.list!!.size > 0) {
                            listAdapter!!.addData(it.data.list!!)
                            refreshList.setEnableLoadMore(true)
                        } else {
                            refreshList.setEnableLoadMore(false)
                            refreshList.finishLoadMoreWithNoMoreData()
                        }
                    }

                    listAdapter!!.notifyDataSetChanged()
                }
            }
        } else {
            viewModel.getDraftPage(IMManager.getInstance().currentId, page, 10) {
                Log.e("total", it.data.total.toString() + "")
                if (refreshList.isRefreshing) {
                    refreshList.finishRefresh()
                }
                if (it.data != null) {
                    if (page == 1) {
                        listAdapter!!.setNewInstance(it.data.list)
                        if (it.data.list!!.size < 10) {
                            refreshList.setEnableLoadMore(false)
                        } else {
                            refreshList.setEnableLoadMore(true)
                        }
                    } else {
                        if (it.data.list!!.size > 0) {
                            listAdapter!!.addData(it.data.list!!)
                            refreshList.setEnableLoadMore(true)
                        } else {
                            refreshList.setEnableLoadMore(false)
                            refreshList.finishLoadMoreWithNoMoreData()
                        }
                    }

                    listAdapter!!.notifyDataSetChanged()
                }
            }
        }

    }

    override fun onItemClick(position: Int, data: CommunityContent?) {
        var pos = 0
        imagesMediaList.clear()
        if (!TextUtils.isEmpty(data!!.files)) {
            if (data!!.files!!.contains(",")) { //多张
                for (i in MyUtils.toList(data!!.files).indices) {
                    val localMedia = LocalMedia()
                    localMedia.path = MyUtils.toList(data!!.files)[i]
                    imagesMediaList.add(localMedia)
                }
                pos = position
            } else {
                val localMedia = LocalMedia()
                localMedia.path = data!!.files
                imagesMediaList.add(localMedia)
                pos = 0
            }
        }
        PictureSelector.create(activity)
            .openPreview()
            .setImageEngine(GlideEngine.createGlideEngine())
            .isPreviewFullScreenMode(true)
//            .isPreviewZoomEffect(true, rlvCampClockImages)
            .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                override fun onPreviewDelete(position: Int) {

                }

                override fun onLongPressDownload(
                    context: Context,
                    media: LocalMedia
                ): Boolean {
                    return true
                }
            })
            .startActivityPreview(pos, false, imagesMediaList)
    }

    override fun onGroupClick(position: Int, data: CommunityContent?) {
        if (IMManager.getInstance().currentId == data!!.userId.toString()) {
            RongIM.getInstance()
                .startGroupChat(context, data!!.groupId.toString(), data!!.groupsName)
        } else {

        }

    }

    override fun onItemLongClick(position: Int, data: CommunityContent?) {
        XPopup.Builder(activity)
            .dismissOnTouchOutside(true)
            .dismissOnBackPressed(true)
            .asBottomList(
                "", arrayOf("下载")
            ) { position, text ->
                if (data!!.pictureDownload == 1) {
                    if (data!!.fileType == 1) { //图片
                        if (!TextUtils.isEmpty(data!!.files)) {
                            if (data!!.files!!.contains(",")) { //多张
                                MyUtils.downloadImage(
                                    activity,
                                    MyUtils.toList(data!!.files)[position]
                                )
                            } else {
                                MyUtils.downloadImage(activity, data!!.files)
                            }
                        }
                    } else {
                        MyUtils.downloadFromNetwork(activity, data!!.files)
                    }
                } else {
                    com.cxh.rmsq.utils.ToastUtils.showToast("不允许下载！")
                }
            }.show()
    }
}